<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
               :disabled="method==='view'"
               label-width="120px">
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="上报渠道" prop="reportChannel"
                          :rules="[
                 ]">
              <el-select v-model="inputForm.reportChannel" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in $dictUtils.getDictList('report_channel')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上报人" prop="reporterId"
                          :rules="[
                 ]">
              <el-input v-model="inputForm.reporterId" placeholder="请填写上报人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName"
                          :rules="[
                 ]">
              <el-input v-model="inputForm.contactName" placeholder="请填写联系人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone"
                          :rules="[
                  {validator: validator.isMobile, trigger:'blur'}
                 ]">
              <el-input v-model="inputForm.contactPhone" placeholder="请填写联系电话"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="设备" prop="deviceId"
                          :rules="[
                 ]">
              <el-select v-model="inputForm.deviceId" placeholder="请选择设备" style="width: 100%;" filterable
                         clearable>
                <el-option
                  v-for="item in deviceList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理状态" prop="status"
                          :rules="[
                 ]">
              <el-select v-model="inputForm.status" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in $dictUtils.getDictList('work_order_status')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障描述" prop="faultDesc"
                          :rules="[
                 ]">
              <el-input type="textarea" :rows="4" v-model="inputForm.faultDesc" placeholder="请填写故障描述"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障图片" prop="faultImg"
                          :rules="[
                 ]">
              <el-upload
                :action="`${$http.BASE_URL}/sys/file/webupload/upload?uploadPath=/workorder/fault`"
                :headers="{token: $cookie.get('token')}"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="(response, file, fileList) => {
                  inputForm.faultImg = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
                }"
                :file-list="faultImgList">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="楼层" prop="floorId"
                          :rules="[
                  { required: true, message: '楼层不能为空', trigger: 'blur' }
                ]">
              <SelectTree ref="floor"
                          :props="{ value: 'id', label: 'showName', children: 'childNodes' }"
                          url="/smis/floor/jfFloor/treeData"
                          :value="inputForm.floorId"
                          :clearable="true"
                          :accordion="true"
                          @getValue="(value) => { inputForm.floorId=value; $refs.selectPoint.showFloor(value); }"/>
            </el-form-item>
          </el-col>

          <!-- 地图选点 -->
          <el-col :span="24" style="height: 400px;">
            <el-form-item label="所在位置" prop="x"
                          :rules="[
                  { required: true, message:'请选择所在位置', trigger:'blur' }
                ]">
              <select-point ref="selectPoint" @onMapClick="mapClick"></select-point>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" v-noMoreClick>确定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import SelectTree from '@/components/treeSelect/treeSelect.vue'
import SelectPoint from '@/components/jfMap/selectPoint.vue'

// 表单验证器
const validator = {
  isMobile (rule, value, callback) {
    if (value && !/^1[3456789]\d{9}$/.test(value)) {
      callback(new Error('请输入正确的手机号码'))
    } else {
      callback()
    }
  }
}

export default {
  data () {
    return {
      title: '',
      method: '',
      visible: false,
      loading: false,
      dialogImageUrl: '',
      dialogVisible: false,
      faultImgList: [],
      deviceList: [], // 设备列表
      inputForm: {
        id: '',
        requestNo: '',
        reportChannel: 'WEB', // 默认为后台录入
        reporterId: '',
        contactName: '',
        contactPhone: '',
        deviceId: '',
        faultDesc: '',
        faultImg: '',
        status: 'PENDING', // 默认为待处理
        floorId: '',
        x: '',
        y: '',
        z: ''
      }
    }
  },
  components: {
    SelectTree,
    SelectPoint
  },
  created () {
    this.getDeviceList()
  },
  watch: {
    'inputForm.floorId' (val) {
      this.$refs.selectPoint && this.$refs.selectPoint.showFloor(val)
      if (val && this.inputForm.x && this.inputForm.y) {
        this.$refs.selectPoint.setMarkPoint(val, this.inputForm.x, this.inputForm.y, this.inputForm.z, true)
      }
    }
  },
  methods: {
    mapClick (point) {
      this.inputForm.x = point.x
      this.inputForm.y = point.y
      this.inputForm.z = point.z
    },
    // 获取设备列表
    getDeviceList () {
      console.log('加载设备数据')
      this.$http({
        url: '/device/equipment/list',
        method: 'get',
        params: {
          pageNo: 1,
          pageSize: 1000
        }
      }).then(({data}) => {
        this.deviceList = data.page?.list || []
      })
    },
    init (method, id) {
      this.method = method
      this.inputForm.id = id
      if (method === 'add') {
        this.title = `新增报修`
        this.getDeviceList()
        // 初始化 floorId, x, y, z 字段
        this.inputForm.floorId = ''
        this.inputForm.x = ''
        this.inputForm.y = ''
        this.inputForm.z = ''
      } else if (method === 'edit') {
        this.title = '修改报修'
      } else if (method === 'view') {
        this.title = '查看报修记录'
      }
      this.visible = true
      this.loading = false
      this.$nextTick(() => {
        this.$refs.inputForm.resetFields()
        // 新增时清空图片列表
        if (method === 'add') {
          this.faultImgList = []
          this.inputForm.faultImg = ''
        } else if (method === 'edit' || method === 'view') { // 修改或者查看
          this.loading = true
          this.$http({
            url: `/workorder/repairRequest/queryById?id=${this.inputForm.id}`,
            method: 'get'
          }).then(({data}) => {
            if (data && data.code === 200) {
              this.inputForm = this.recover(this.inputForm, data.repairRequest)
              this.initFaultImgList()
              // 如果有楼层和坐标信息，设置地图标记点
              if (this.inputForm.floorId && this.inputForm.x && this.inputForm.y) {
                this.$nextTick(() => {
                  this.$refs.selectPoint && this.$refs.selectPoint.showFloor(this.inputForm.floorId)
                  this.$refs.selectPoint && this.$refs.selectPoint.setMarkPoint(
                    this.inputForm.floorId,
                    this.inputForm.x,
                    this.inputForm.y,
                    this.inputForm.z || 0,
                    true
                  )
                })
              }
            } else {
              this.$message.error(data.msg || '获取报修记录失败')
            }
            this.loading = false
          }).catch((error) => {
            this.loading = false
            this.$message.error('获取报修记录失败')
          })
        }
      })
    },
    // 表单提交
    doSubmit () {
      this.$refs['inputForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.$http({
            url: `/workorder/repairRequest/save`,
            method: 'post',
            data: this.inputForm
          }).then(({data}) => {
            if (data && data.success) {
              this.visible = false
              this.$message.success(data.msg)
              this.$emit('refreshDataList')
            }
            this.loading = false
          })
        }
      })
    },
    // 处理图片预览
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 处理图片移除
    handleRemove (file, fileList) {
      this.$http.post(`/sys/file/webupload/deleteByUrl?url=${(file.response && file.response.url) || file.url}`).then(({data}) => {
        this.$message.success(data.msg)
      })
      this.inputForm.faultImg = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
    },
    // 处理已有图片的显示
    initFaultImgList () {
      if (this.inputForm.faultImg) {
        const imgUrls = this.inputForm.faultImg.split('|')
        this.faultImgList = imgUrls.map(url => {
          const fileName = url.substring(url.lastIndexOf('/') + 1)
          return {
            name: fileName,
            url: url
          }
        })
      } else {
        this.faultImgList = []
      }
    },
    // 恢复表单数据
    recover (form, source) {
      if (source && typeof source === 'object') {
        Object.keys(form).forEach(key => {
          if (source[key] !== undefined && source[key] !== null) {
            form[key] = source[key]
          }
        })
      }
      return form
    }
  }
}
</script>
